#!/bin/bash

set -eu

tag="$1"
v="${tag:1}"

# Build pip package
rm -rf build/ dist/ *.egg-info/
local_settings=$(ls -1 squad/local_settings.py 2>/dev/null || true)
if [ -n "$local_settings" ]; then
    mv "$local_settings" "$local_settings".off
fi
python3 setup.py sdist bdist_wheel

# test
tar=$(mktemp tar.XXXXXXXXX)
git=$(mktemp git.XXXXXXXXX)
trap cleanup INT TERM EXIT
cleanup() {
    rm -rf "$tar" "$git"
    if [ -n "$local_settings" ]; then
        mv "$local_settings".off "$local_settings"
    fi
}
git ls-tree -r --name-only HEAD | grep -v '\.tar$' | sort > "$git"

downloads=$(awk '{ if ($1 && $1 !~ /^#/) { print($1)} }' squad/frontend/static/download.conf | xargs printf '%s\|')
tar taf dist/squad-${v}.tar.gz | cut -d / -f 2- | grep -v '\(/$\|^$\|PKG-INFO\|egg-info\|static\/\('$downloads'download.status\)\|.mo$\)' | sort > "$tar"
diff -u "$tar" "$git"

# Build docker container
docker build -t squadproject/squad:$v .
